package com.example.message.controller;

import java.time.LocalDateTime;
import java.util.List;

import com.example.message.entity.Message;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.message.dto.MessageSendDTO;
import com.example.message.service.MessageService;
import com.example.message.vo.MessageVO;
import com.example.project.core.controller.BaseController;
import com.example.project.core.domain.AjaxResult;
import com.example.project.core.page.TableDataInfo;
import com.example.project.entity.Position;
import com.example.project.entity.Role;
import com.example.project.entity.User;
import com.example.project.service.PositionService;
import com.example.project.service.RoleService;
import com.example.project.service.UserService;

/**
 * 通知控制器
 */
@Controller
@RequestMapping("system/message")
public class MessageController extends BaseController {

	private String prefix = "system/message";

	@Autowired
	private MessageService messageService;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PositionService positionService;

	@RequiresPermissions("system:message:view")
	@GetMapping()
	public String message() {
		return prefix + "/message";
	}

	/**
	 * 查询消息列表
	 */
	@RequiresPermissions("system:message:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Message message) {
		startPage();
		List<Message> list = messageService.selectMessageList(message);
		return getDataTable(list);
	}

	@RequiresPermissions("system:message:receive")
	@GetMapping("receive")
	public String receiveMessage(ModelMap mmap) {
		mmap.put("curUserId", getUserId());
		return prefix + "/message_receive";
	}

	/**
	 * 新增消息
	 */
	@RequiresPermissions("system:message:add")
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		// 用户
		List<User> userList = userService.findAllList();
		mmap.put("userList", userList);
		
		List<Role> roleList = roleService.selectRoleAll();
		mmap.put("roleList", roleList);
		
		List<Position> positions = positionService.selectPostAll();
		mmap.put("positions", positions);
		return prefix + "/message_send";
	}

	/**
	 * 发送通知
	 */
	@ResponseBody
	@PostMapping("/send")
	public AjaxResult send(@Validated MessageSendDTO messageSendDTO) {
		// 将DTO转换为实体
		Message message = convertToMessage(messageSendDTO);
		message.setSenderId(getUserId());
		message.setSenderName(getUser().getUserName());
		message.setCreateTime(LocalDateTime.now());
		message.setSendTime(LocalDateTime.now());
		message.setStatus(1); // 已发送
		return toAjax(messageService.sendMessage(message));
	}

	/**
	 * 使用模板发送通知
	 */
	@PostMapping("/send/template")
	public AjaxResult sendByTemplate(@RequestBody MessageSendDTO messageSendDTO) {
		// 将DTO转换为实体
		Message message = convertToMessage(messageSendDTO);
		message.setSenderId(getUserId());
		message.setCreateTime(LocalDateTime.now());
		message.setSendTime(LocalDateTime.now());
		message.setStatus(1); // 已发送
		return toAjax(messageService.sendMessageByTemplate(message));
	}

	/**
	 * 将MessageSendDTO转换为Message实体
	 */
	private Message convertToMessage(MessageSendDTO dto) {
		Message message = new Message();
		message.setTitle(dto.getTitle());
		message.setContent(dto.getContent());
		message.setMessageType(dto.getMessageType());
		message.setSendMethod(dto.getSendMethod());
		message.setPriority(dto.getPriority());
		message.setTargetType(dto.getTargetType());
		message.setTargetIds(dto.getTargetIds());
		message.setBusinessType(dto.getBusinessType());
		message.setBusinessId(dto.getBusinessId());
		message.setExpireTime(dto.getExpireTime());
		return message;
	}

	/**
	 * 获取通知详情
	 */
	@GetMapping("/view/{messageId}")
	public String getInfo(@PathVariable("messageId") Long messageId, ModelMap mmap) {
		MessageVO messageVO = messageService.selectMessageById(messageId);
		mmap.put("message", messageVO);
		return prefix + "/message_view";
	}

	/**
	 * 删除通知
	 */
	@DeleteMapping("/remove/{messageIds}")
	public AjaxResult remove(@PathVariable Long[] messageIds) {
		return toAjax(messageService.deleteMessageByIds(messageIds));
	}

	/**
	 * 获取用户通知列表
	 */
	@RequiresPermissions("system:message:list")
	@PostMapping("/user/list")
	@ResponseBody
	public TableDataInfo userList(Message message) {
		startPage();
		List<Message> list = messageService.getUserMessageList(getUserId(), message.getMessageType(),
				message.getReadStatus());
		return getDataTable(list);
	}

	/**
	 * 获取用户未读通知数量
	 */
	@RequiresPermissions("system:message:list")
	@GetMapping("/user/unread/count")
	@ResponseBody
	public AjaxResult getUnreadCount(Long userId) {
		if (userId == null) {
			userId = getUserId();
		}
		Long count = messageService.getUnreadCount(userId);
		return success(count);
	}

	/**
	 * 标记通知为已读
	 */
	@PostMapping("/mark/read/{messageId}")
	@ResponseBody
	public AjaxResult markAsRead(@PathVariable Long messageId) {
		return toAjax(messageService.markAsRead(messageId, getUserId()));
	}

	/**
	 * 批量标记为已读
	 */
	@PostMapping("/mark/read/batch")
	@ResponseBody
	public AjaxResult batchMarkAsRead(@RequestBody List<Long> receiveIds) {
		return toAjax(messageService.batchMarkAsRead(receiveIds, getUserId()));
	}

	/**
	 * 处理通知
	 */
	@PostMapping("/handle/{receiveId}")
	@ResponseBody
	public AjaxResult handleMessage(@PathVariable Long receiveId, @RequestParam Integer handleStatus,
			@RequestParam(required = false) String handleRemark) {
		return toAjax(messageService.handleMessage(receiveId, getUserId(), handleStatus, handleRemark));
	}

	/**
	 * 查看接收通知详情
	 */
	@GetMapping("/receive/view/{receiveId}")
	@ResponseBody
	public AjaxResult viewMessage(@PathVariable Long receiveId) {
		MessageVO messageVO = messageService.viewMessage(receiveId, getUserId());
		return success(messageVO);
	}

	/**
	 * 获取新通知（用于右下角弹窗）
	 */
	@GetMapping("/notifications/new")
	@ResponseBody
	public AjaxResult getNewNotifications(@RequestParam(required = false) Long lastCheckTime) {
		List<MessageVO> newNotifications = messageService.getNewNotifications(getUserId(), lastCheckTime);
		return success(newNotifications);
	}
}